import websockets
import asyncio
import json

# 第1步，创建1个虚拟页，在虚拟页面上进行录制
# "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222
async def enable_network():
    uri = "ws://localhost:9222/devtools/page/E29711532410F46C9D0C9803AD9B204C"
    async with websockets.connect(uri) as websocket:
        # Send the Network.enable command
        await websocket.send(json.dumps({"id": 1, "method": "Network.enable"}))

        while True:
            result = await websocket.recv()
            message = json.loads(result)

            # Check for network events
            if "method" in message:
                if message["method"] == "Network.responseReceived":
                    print("Response headers received!")
                    print(message)
                elif message["method"] == "Network.loadingFinished":
                    print("Response body received!")
                    loading_finished_id = message["params"]["requestId"]
                    await websocket.send(json.dumps({"id": 2, "method": "Network.getResponseBody", "params": {"requestId": loading_finished_id}}))
                    result3 = await websocket.recv()
                    print(result3)
                elif message["method"] == "Network.getResponseBody":
                    print("Response body:")
                    print(message["params"]["body"])
                elif message["method"].startswith("Network."):
                    print(message)

asyncio.get_event_loop().run_until_complete(enable_network())
